import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { CodeParserService } from './code-parser.service';

export interface CustomFunction {
  id: string;
  name: string;
  code: string;
  params: string[];
  hasReturnValue: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class CustomFunctionService {
  private apiUrl = 'http://localhost:8000/custom_scripts';
  
  constructor(
    private http: HttpClient,
    private codeParser: CodeParserService
  ) {}
  
  /**
   * 从API获取自定义函数列表
   */
  getCustomFunctions(): Observable<CustomFunction[]> {
    return this.http.get<any[]>(this.apiUrl).pipe(
      map(response => {
        // 假设API返回的是包含函数代码的数组
        return response.map((item, index) => {
          const { funcName, params } = this.codeParser.parseFunction(item || '');
          const hasReturnValue = this.codeParser.hasReturnValue(item || '');
          
          return {
            id: item.id || `func_${index}`,
            name: funcName || `未命名函数_${index}`,
            code: item || '',
            params: params,
            hasReturnValue: hasReturnValue
          };
        });
      })
    );
  }
} 